package com.tedu.egspringbootmvc.controller;



import com.tedu.egspringbootmvc.mapper.UserMapping;
import com.tedu.egspringbootmvc.pojo.dto.UserArticleDTO;
import com.tedu.egspringbootmvc.pojo.dto.UserLoginDTO;
import com.tedu.egspringbootmvc.pojo.entity.Article;
import com.tedu.egspringbootmvc.pojo.entity.User;
import com.tedu.egspringbootmvc.pojo.vo.ArticleVO;
import com.tedu.egspringbootmvc.result.JsonResult;
import com.tedu.egspringbootmvc.result.StatusCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "用户模块")
@RestController
@RequestMapping("/v1/users")
@Validated
public class UserController {

    @Autowired
    private UserMapping userMapping;

    @ApiOperation("登录功能")
    @PostMapping("/login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        User user=userMapping.selectByUsername(userLoginDTO.getUsername(),userLoginDTO.getPassword());
        System.out.println("用户:"+user);

        if(user!=null){
                session.setAttribute("user", user);
            System.out.println("用户:"+user);
                return JsonResult.success();
            }else {
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }

    }

    @ApiOperation("发表文章功能")
    @PostMapping("/article")
    public JsonResult article(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        User user=(User)session.getAttribute("user");
        if (user!=null){
            Article a =new Article();

            BeanUtils.copyProperties(userArticleDTO,a);
            a.setUserId(user.getId());
            userMapping.insert(a);
            return JsonResult.success();
        }else {
            return new JsonResult(StatusCode.NOT_LOGIN);
        }
    }

    @ApiOperation("查询指定文章功能")
    @GetMapping("/selectByArticleId")
    @ApiImplicitParam(name="id",value = "文章ID",required = true,example = "10")
    public JsonResult selectByArticleId(@Range(min=1,max =100,message = "文章的ID必须在1-100之间") int id){
        ArticleVO article=userMapping.selectByArticleId(id);
        return JsonResult.success(article);
    }





}
